package _08_DFS;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/permutations/
 * @Author: haogege
 * @Date: 2021/8/31
 */
public class _46_全排列2 {

    // 采用替换策略
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        if (nums.length == 1) {
            List<Integer> result = new ArrayList<>();
            result.add(nums[0]);
            list.add(result);
            return list;
        }
        dfs(0, nums, list);
        return list;
    }

    private void dfs(int i, int[] nums, List<List<Integer>> list) {
        if (i == nums.length) {
            List<Integer> result = new ArrayList<>();
            for (int k : nums) {
                result.add(k);
            }
            list.add(result);
            return;
        }

        // 遍历当前层的所有结果
        for (int j = i; j < nums.length; j++) {
            if (i != j) {
                swap(nums, i, j);
                dfs(i + 1, nums, list);
                swap(nums, i, j);
            } else {
                dfs(i + 1, nums, list);
            }
        }
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }

}
